<template>

  <div style="padding:0px 8px">

    <el-card shadow="always" class="configContainer">
      <div style="display: flex;flex-direction: row;align-items: center">
        <h4 class="card-title"> 用户管理 </h4>
        <div class="space"/>
        <el-button type="primary" @click="dialogVisible = true">新增用户</el-button>
      </div>
      <el-divider/>
      <div style="margin: 8px">
        <div class="searchDiv">
          <el-input clearable v-model="searchForm.userName" placeholder="请输入账号" style="width:200px;margin-right: 16px;"/>
          <el-input clearable v-model="searchForm.phone" placeholder="请输入手机号" style="width:200px;margin-right: 16px;"/>
          <el-input clearable v-model="searchForm.nickName" placeholder="请输入昵称" style="width:200px;margin-right: 16px;"/>
          <el-button type="primary" @click="search()">
            <el-icon>
              <Search/>
            </el-icon>
            搜索
          </el-button>
          <el-button @click="reset()">重置</el-button>
        </div>


        <div style="width: 100%;position: relative;margin-top: 16px">
          <el-table height="400px" :header-cell-style="{background:'#f8f8f8',height:'40px',color:'#2b2b2b'}" :data="tableData">
            <el-table-column fixed prop="id" label="编号" min-width="30"/>
            <el-table-column fixed prop="nickName" label="昵称" min-width="60"/>
            <el-table-column prop="userName" label="账号" min-width="60"/>
            <el-table-column prop="phone" label="手机号" min-width="60"/>
            <el-table-column prop="schoolName" label="所属学校" min-width="60"/>
            <el-table-column prop="descriptions" label="角色" min-width="60">
              <template #default="scope">
                <span class="cursor" @click="showJson(scope.row.descriptions)">{{ scope.row.descriptions }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否启用" min-width="60">
              <template #default="scope">
                <el-switch :disabled="scope.row.id === user?.id" v-model="scope.row.enable"
                           @change="changeSwitch(scope.row.id, scope.row.enable)"/>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="注册日期" min-width="60"/>
            <el-table-column fixed="right" label="操作" width="120">
              <template #default="scope">
                <el-button v-if="user?.id !==scope.row.id" link type="primary" size="small" @click="currUserInfo(scope.row)">
                  <el-icon>
                    <Edit/>
                  </el-icon>
                  编辑
                </el-button>

                <el-popconfirm title="确认删除吗?" v-if="user?.id !==scope.row.id" @confirm="deleteUser(scope.row.id)">
                  <template #reference>
                    <el-button link size="small" type="danger">

                      <el-icon>
                        <Delete/>
                      </el-icon>删除</el-button>
                  </template>
                </el-popconfirm>

              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
            :page-sizes="[10, 20, 50, 100]"
             :page-count="pagecount"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="currentChange"
                       style="margin-top: 16px;width: 100%;display: flex;align-items: center;justify-content: center;"
                       background layout="total, sizes, prev, pager, next, jumper"/>

      </div>
    </el-card>
  </div>

  <el-dialog title="新增用户" v-model="dialogVisible" width="30%">
    <!--弹出的对话框的内容-->
    <el-form ref="add" :model="addForm" label-width="80px" :rules="addRules">
      <el-form-item label="账号" prop="userName">
        <el-input v-model="addForm.userName" maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="学校" prop="schoolId">
        <el-select v-model="addForm.schoolId" placeholder="请选择学校" style="width:100%">
          <el-option v-for="item in schoolList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password" maxlength="10" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkpassword">
        <el-input v-model="addForm.checkpassword" maxlength="10" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="addForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="addForm.nickName"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-cascader style="width: 100%" :options="roleList" v-model="addForm.role" :props="props" clearable/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="register()">确 定</el-button>
    </template>
  </el-dialog>

  <el-dialog title="编辑用户" v-model="changVisible" width="30%">
    <el-form ref="edit" :model="userInfo" label-width="80px" :rules="rules">
      <el-form-item label="用户编号">
        <el-input v-model="userInfo.id" maxlength="10" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="userInfo.userName" maxlength="11" disabled></el-input>
      </el-form-item>
      <el-form-item label="学校" prop="schoolId">
        <el-select v-model="userInfo.schoolId" placeholder="请选择学校" style="width:100%">
          <el-option v-for="item in schoolList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userInfo.phone"></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="userInfo.nickName"></el-input>
      </el-form-item>
      <el-form-item label="权限" prop="role">
        <!-- <el-cascader :options="roleList" :props="{label:'description',value:'id' ,multiple: true }"  clearable />-->
        <el-cascader style="width: 100%" :options="roleList" v-model="userInfo.role" :props="props" change-on-select/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="changVisible = false">取 消</el-button>
      <el-button type="primary" @click="updateInfo()">确 定</el-button>
    </template>
  </el-dialog>

  <!-- 删除按键弹窗 -->
  <el-dialog v-model="show" title="权限信息" center>
    <json-viewer
        :expand-depth=5
        copyable
        boxed
        sort="true"
        :value="JsonData">
    </json-viewer>
  </el-dialog>
  <CompanyText/>
</template>


<script>

import CompanyText from "../../../components/CompanyText.vue";

export default {
  name: 'userConfig',
  props: {},
  components: {
    CompanyText
  },
  data() {
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      user:{},
      pagecount:100,
      total:100,
      JsonData: [],
      show: false,
      schoolList: [],
      tableData: [],
      props: {multiple: true},
      dialogVisible: false,
      changVisible: false,
      isDisabled: true,
      addForm: {
        userName: "",
        password: "",
        checkpassword: "",
        phone: "",
        nickName: "",
        schoolId: null,
        role: [],
        schoolName: ""
      },
      searchForm: {
        size: 6,
        current: 1,
        userName: "",
        phone: "",
        nickName: ""
      },
      rules: {
        password: [{required: true, message: "没有填写密码", tirgger: blur}, {
          min: 5,
          max: 12,
          message: "长度5到10个字符",
          tirgger: blur
        }],
        role: [{required: true, message: '权限必选', trigger: ['change'], type: 'array'}],
        schoolId: [{required: true, message: '学校必选', trigger: ['change'], type: 'number'}],
        userName: [{required: true, message: "没有填写账号", tirgger: blur},],
        checkpassword: [{validator: validatePass2, tirgger: blur}],
        phone: [
          {required: false, trigger: 'blur'},
          {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur'}
        ]
      },
      addRules: {
        password: [{required: true, message: "没有填写密码", tirgger: blur}, {
          min: 5,
          max: 12,
          message: "长度5到10个字符",
          tirgger: blur
        }],
        phone: [
          {required: false, trigger: 'blur'},
          {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur'}
        ],
        role: [{required: true, message: '权限必选', trigger: ['change'], type: 'array'}],
        schoolId: [{required: true, message: '学校必选', trigger: ['change'], type: 'number'}],
        userName: [{required: true, message: "没有填写账号", tirgger: blur},],
        checkpassword: [{required: true, message: "确认密码必填"}, {validator: validatePass2, tirgger: blur}],
      },
      userInfo: {
        id: "",
        userName: "",
        phone: "",
        nickName: "",
        schoolId: 1,
        role: [[1], [2], [3], [4], [5]],
      },
      loginInfo: {
        userName: "",
        password: "",
        checkpassword: "",
        phone: "",
        nickName: "",
        schoolId: 1,
        schoolName: ""
      },
      roleList: []
    }
  },
  mounted() {

  },
  created() {
    this.getRuleList();
    this.search();
    this.getAllSchool();
    this.getUser();
  },
  methods: {
    getUser() {
      this.user = JSON.parse(window.localStorage.getItem('user'));
    },
    showJson(role) {
      this.show = true;
      if (role == null) {
        this.JsonData = [];
        return;
      }
      this.JsonData = role.split(",");
      console.info(this.JsonData)
    },
    reset() {
      this.searchForm = {};
      this.search();
    },

    getRuleList() {
      this.$http.post("/role/getRuleList")
          .then(res => {
            this.roleList = res.data
          }).catch(err => {
      })
    },
    search() {
      this.$http.post("/user/search", this.searchForm)
          .then(res => {
            this.tableData = res.data.records;
            this.pagecount = res.data.pages;
            this.total = res.data.total;
            this.searchForm.current = res.data.current;
          }).catch(err => {
      })
    },
    getAllSchool() {
      this.$http.post('/school/getAllSchoolList')
          .then(res => {
            this.schoolList = res.data;
          }).catch(err => {
      })
    },
    register() {
      this.$refs.add.validate((valid, fields) => {
        if (valid) {
          this.$http.post("/user/register", this.addForm)
              .then(res => {
                if (res.code === 0) {
                  this.$message.success(res.userMsg)
                  this.dialogVisible = false
                  this.search()
                  this.$refs.add.resetFields()
                }
              }).catch(err => {
          })
        }
      })
    },
    updateInfo() {
      this.$refs.edit.validate((valid, fields) => {
        if(valid){
          this.$http.post("/user/updateUserById", this.userInfo)
              .then(res => {
                if (res.code === 0) {
                  this.changVisible = false
                  this.$message.success(res.userMsg)
                  this.$refs.edit.resetFields()
                }
                this.search()
              }).catch(err => {
          })
        }
      })
    },
    deleteUser(id) {
      this.$http.get("user/deleteUser", {
        params: {
          id: id
        }
      }).then(res => {
        if (res.code === 0) {
          this.$message.success(res.userMsg)
        }
        this.search()
      }).catch(err => {
      })
    },
    changeSwitch(id, type) {
      this.$http.get("user/changSwitch", {
        params: {
          id: id,
          type: type
        }
      }).then(res => {
        if (res.code === 0) {
          this.$message.success(res.userMsg)
        }
      }).catch(err => {
      })
    },
    currUserInfo(item) {
      this.changVisible = true
      this.userInfo = {...item}
      let arr = item.roleIds.split(",")
      this.userInfo.role = [];
      for (const arrElement of arr) {
        this.userInfo.role.push([parseInt(arrElement)])
      }
      console.log(JSON.stringify(this.userInfo.role))
    },

    currentChange(current) {
      this.searchForm.current = current;
      console.info(this.current)
      this.search();
    },
    handleSizeChange(size) {
      this.searchForm.size = size;
      console.info(this.size)
      this.search();
    },

  }
}
</script>

<style scoped>

.configContainer {
  margin: 10px 8px;
  padding: 0px;
  /* border: red 1px solid; */
}

.cursor {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

</style>
